import 'package:flutter/material.dart';
import 'package:zhibao_flutter/util/check/click_event.dart';
import 'package:zhibao_flutter/util/event_bus/refresh_event_bus.dart';

import 'package:zhibao_flutter/util/float/fram_size.dart';
import 'package:zhibao_flutter/util/func/log.dart';

class FloatUtil {
  static double viewHeight = (138.5); //浮窗中画面的高
  static OverlayEntry? overlayEntry;

  static void showOverlayEntry({
    required BuildContext context,
  }) {
    removeOverlayEntry();

    /// 一定要延时，否则：
    /// "iOS主播退桌面，然后回直播间，立刻切小窗口，小窗口消失"
    overlayEntry = OverlayEntry(builder: (context) {
      return const DraggableView();
    });

    //往Overlay中插入插入OverlayEntry
    Overlay.of(context, rootOverlay: true)!.insert(overlayEntry!);
  }

  static void removeOverlayEntry() {
    if (overlayEntry != null) {
      overlayEntry?.remove();
      overlayEntry = null;
    }
  }
}

class DraggableView extends StatefulWidget {
  const DraggableView({Key? key}) : super(key: key);

  @override
  State<DraggableView> createState() => _DraggableViewState();
}

class _DraggableViewState extends State<DraggableView> {
  double _left = FrameSize.screenW() - (60 * 1.5);
  double _top = FrameSize.statusBarHeight();

  /// 尺寸
  double itemSize = 42;

  Widget _draggableView(BuildContext context) {
    return ClickEvent(
      onTap: () async {
        LogUtil.d("FloatUtil call refresh page");
        refreshEventBus.fire(RefreshEventBusModel());
      },
      child: Container(
        width: itemSize,
        height: itemSize,
        alignment: Alignment.center,
        child: Image.asset(
          "assets/images/other/float_refresh.png",
          width: 29.5,
          height: 29.5,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
      /// 【2021 11.25】优化小窗口位置（安卓苹果统一）
      /// 直播UI验收11.16 - 飞书云文档   【商品分享】安卓、IOS分享商品，都会出现挡住
      top: _top,
      left: _left,
      child: GestureDetector(
        // 移动中
        onPanUpdate: (details) {
          setState(() {
            _top = details.globalPosition.dy;
            _left = details.globalPosition.dx;
          });
        },
        // 移动结束
        onPanEnd: (details) {
          setState(() {
            if (_top <= (FrameSize.padTopH() + 5.5)) {
              _top = FrameSize.padTopH() + 5.5;
            }

            if (_top >= FrameSize.screenH()) {
              _top = FrameSize.screenH() - itemSize;
            }

            if (_left > FrameSize.winWidth() - itemSize) {
              _left = FrameSize.screenW() - itemSize;
            }
          });
        },

        child: ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: Material(
            type: MaterialType.transparency,
            child: _draggableView(context),
          ),
        ),
      ),
    );
  }
}
